package com.penghk.earth.util;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

public class HttpClientUtil {
        private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    private static String charSet = "UTF-8";

    /**
     *
     * @param url
     * @param keyvalues
     * @return
     */
    public static String doGet(String url , Map<String ,String > keyvalues) {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("bad http request");
            }
            Header[] headers = getMethod.getResponseHeaders();
            for(Header header : headers) {
                System.out.println(header.getName()+" : "+header.getValue());
            }
            Header header = getMethod.getResponseHeader("Content-Type");
            HeaderElement[] elements = header.getElements();
            for (HeaderElement element : elements) {
                System.out.println(element.getName());
                NameValuePair pair = element.getParameterByName("charset");
                charSet = pair.getValue();
                System.out.println(pair.getValue());
            }
            byte[] responseByres = getMethod.getResponseBody();
            System.out.println(new String(responseByres,charSet));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }
}
